package com.mayn.util;

import java.util.Set;
import org.openqa.selenium.Cookie;

/**
 * Cookie处理工具类
 * 
 * @author dadao
 * 
 */
public class CookieUtil {

	
    /**
     * Set<Cookie> 转换为 字符串
     * @param cookieSet
     * @return
     */
    public static String getCookieStr( Set<Cookie> cookieSet) {
		String cookieStr = "";
		if (cookieSet == null) {
			return cookieStr;
		} else {
			for (Cookie ck : cookieSet) {
				cookieStr = cookieStr + ";" + ck.getName() + "=" + ck.getValue();
			}
			if (cookieStr.startsWith(";")) {
				cookieStr = cookieStr.substring(1, cookieStr.length());
			}
		}
		return cookieStr;
	}
    
    /**
     * 
     * @param str
     * @return
     */
    public static Cookie[] getCookieByStr(String str) {
		String[] cookiestrs = str.split(";");
		Cookie[] cookies = new Cookie[cookiestrs.length];
		for (int i = 0; i < cookies.length; i++) {
			if (cookiestrs[i].contains("=")) {
				String[] onecookie = cookiestrs[i].trim().split("=");
				if (onecookie.length > 2) {
					String value = cookiestrs[i].substring(onecookie[0].length() + 2, cookiestrs[i].length());
					cookies[i] = new Cookie(onecookie[0].trim(), value.trim());
				} else {
					if (onecookie.length == 2) {
						cookies[i] = new Cookie(onecookie[0].trim(), onecookie[1].trim());
					} else {
						cookies[i] = new Cookie(onecookie[0].trim(), "");
					}
				}
			} else {
				cookies[i] = new Cookie(cookiestrs[i].trim(), "");
			}
		}
		return cookies;
	}
    
    /**
     * 
     * @param cookies
     * @param name
     * @return
     */
	public static String getCookieByName(Cookie[] cookies, String name) {
		String ret = "";
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals(name)) {
				return cookies[i].getValue();
			}
		}
		return ret;
	}
}
